/**
 * 课程详情页面
 * /packageTeacher/pages/courses/detail/index
 */

const Router = require('../../../utils/router')
const Storage = require('../../../utils/storage')
const Logger = require('../../../utils/logger')
const Track = require('../../../utils/track')
const Auth = require('../../../utils/auth')
const { TeacherService } = require('../../../services/index')

Page({
  data: {
    title: '课程详情',
    loading: true,
    courseId: '',
    course: null,
    userCourse: null,
    
    // 页面状态
    showVideo: false,
    currentVideoIndex: 0,
    
    // 购买相关
    showPurchase: false,
    purchasing: false,
    
    // 收藏状态
    favorited: false,
    favoriteing: false,
    
    // 推荐课程
    recommendCourses: []
  },

  onLoad(options) {
    const { id } = options
    this.setData({ courseId: id })
    
    Logger.info('Page loaded: /packageTeacher/pages/courses/detail/index', { courseId: id })
    Track.trackPageView('/packageTeacher/pages/courses/detail/index', { courseId: id })
    
    this.loadCourseDetail()
  },

  onShow() {
    // 检查登录状态
    this.checkLoginStatus()
    
    // 检查用户课程状态
    this.checkUserCourseStatus()
  },

  /**
   * 加载课程详情
   */
  async loadCourseDetail() {
    try {
      this.setData({ loading: true })
      
      // 调用API获取课程详情
      const course = await TeacherService.getCourseDetail(this.data.courseId)
      
      if (!course) {
        throw new Error('课程不存在')
      }
      
      this.setData({ course })
      
      // 设置导航栏标题
      wx.setNavigationBarTitle({
        title: course.title || '课程详情'
      })
      
      // 加载推荐课程
      this.loadRecommendCourses()
      
      Track.trackEvent('course_detail_view', {
        course_id: this.data.courseId,
        course_title: course.title
      })
      
    } catch (error) {
      Logger.error('Failed to load course detail', error)
      wx.showToast({
        title: error.message || '加载失败',
        icon: 'none'
      })
      
      setTimeout(() => {
        wx.navigateBack()
      }, 1500)
    } finally {
      this.setData({ loading: false })
    }
  },

  /**
   * 加载推荐课程
   */
  async loadRecommendCourses() {
    try {
      const { course } = this.data
      if (!course) return
      
      // 根据分类获取相关课程
      const params = {
        category_id: course.category_id,
        limit: 6,
        exclude_id: this.data.courseId
      }
      
      const result = await TeacherService.getCourseList(params)
      const courses = Array.isArray(result) ? result : (result.courses || result.data || [])
      
      this.setData({ recommendCourses: courses })
      
    } catch (error) {
      Logger.error('Failed to load recommend courses', error)
    }
  },

  /**
   * 检查登录状态
   */
  checkLoginStatus() {
    const isLoggedIn = Auth.isLoggedIn()
    this.setData({ isLoggedIn })
  },

  /**
   * 检查用户课程状态
   */
  async checkUserCourseStatus() {
    try {
      if (!Auth.isLoggedIn()) return
      
      const userInfo = Auth.getUserInfo()
      const userCourses = await TeacherService.getUserCourseList({ 
        user_id: userInfo.id,
        course_id: this.data.courseId 
      })
      
      const userCourse = userCourses.find(uc => uc.course_id == this.data.courseId)
      this.setData({ userCourse })
      
    } catch (error) {
      Logger.error('Failed to check user course status', error)
    }
  },

  /**
   * 播放视频
   */
  onPlayVideo(e) {
    const { index = 0 } = e.currentTarget.dataset
    this.setData({
      showVideo: true,
      currentVideoIndex: index
    })
    
    Track.trackClick('course_video_play', 'video', { 
      courseId: this.data.courseId,
      videoIndex: index 
    })
  },

  /**
   * 关闭视频
   */
  onCloseVideo() {
    this.setData({ showVideo: false })
  },

  /**
   * 查看教师详情
   */
  onViewTeacher() {
    const { course } = this.data
    if (!course?.teacher_id) return
    
    Track.trackClick('course_teacher_view', 'navigation', { teacher_id: course.teacher_id })
    Router.navigateTo(`/packageTeacher/pages/detail/index?id=${course.teacher_id}`)
  },

  /**
   * 收藏课程
   */
  async onFavorite() {
    if (!Auth.isLoggedIn()) {
      this.showLoginTip()
      return
    }
    
    if (this.data.favoriteing) return
    
    this.setData({ favoriteing: true })
    
    try {
      const { favorited } = this.data
      
      // 调用收藏/取消收藏API
      // 注意：这里需要根据实际API接口来实现
      // await TeacherService.toggleCourseFavorite(this.data.courseId)
      
      this.setData({ favorited: !favorited })
      
      wx.showToast({
        title: favorited ? '已取消收藏' : '已收藏',
        icon: 'success'
      })
      
      Track.trackEvent(favorited ? 'course_unfavorite' : 'course_favorite', {
        course_id: this.data.courseId
      })
      
    } catch (error) {
      Logger.error('Failed to toggle favorite', error)
      wx.showToast({
        title: '操作失败',
        icon: 'none'
      })
    } finally {
      this.setData({ favoriteing: false })
    }
  },

  /**
   * 分享课程
   */
  onShareCourse() {
    Track.trackClick('course_share', 'action', { courseId: this.data.courseId })
    // 微信分享会自动处理
  },

  /**
   * 立即购买
   */
  async onPurchase() {
    if (!Auth.isLoggedIn()) {
      this.showLoginTip()
      return
    }
    
    if (this.data.userCourse) {
      wx.showToast({
        title: '您已购买此课程',
        icon: 'none'
      })
      return
    }
    
    this.setData({ purchasing: true })
    
    try {
      const userInfo = Auth.getUserInfo()
      const { course } = this.data
      
      // 创建订单
      const order = await TeacherService.createOrder({
        user_id: userInfo.id,
        course_id: course.id,
        teacher_id: course.teacher_id,
        amount: course.price || course.current_price,
        type: 'course'
      })
      
      // 调用支付
      await this.processPay(order.id)
      
      Track.trackClick('course_purchase', 'action', { courseId: this.data.courseId })
      
    } catch (error) {
      Logger.error('Failed to purchase course', error)
      wx.showToast({
        title: error.message || '购买失败',
        icon: 'none'
      })
    } finally {
      this.setData({ purchasing: false })
    }
  },

  /**
   * 处理支付
   */
  async processPay(orderId) {
    try {
      // 调用支付API
      const payResult = await TeacherService.payOrder(orderId)
      
      if (payResult.success) {
        // 支付成功，注册用户课程
        const userInfo = Auth.getUserInfo()
        await TeacherService.registerUserCourse({
          user_id: userInfo.id,
          course_id: this.data.courseId,
          order_id: orderId
        })
        
        wx.showToast({
          title: '购买成功',
          icon: 'success'
        })
        
        // 重新检查用户课程状态
        this.checkUserCourseStatus()
        
        Track.trackEvent('course_purchase_success', {
          course_id: this.data.courseId,
          order_id: orderId
        })
        
      } else {
        throw new Error(payResult.message || '支付失败')
      }
      
    } catch (error) {
      Logger.error('Payment failed', error)
      throw error
    }
  },

  /**
   * 开始学习
   */
  onStartStudy() {
    if (!this.data.userCourse) {
      wx.showToast({
        title: '请先购买课程',
        icon: 'none'
      })
      return
    }
    
    Track.trackEvent('course_study_start', {
      course_id: this.data.courseId
    })
    
    // TODO: 需要创建学习页面
    wx.showToast({
      title: '学习功能开发中',
      icon: 'none'
    })
    // Router.navigateTo(`/packageTeacher/pages/courses/study/index?id=${this.data.courseId}`)
  },

  /**
   * 试听课程
   */
  onTryListen() {
    Track.trackClick('course_try_listen', 'action', { courseId: this.data.courseId })
    
    // 找到第一个免费课时
    let freeLesson = null
    const { course } = this.data
    if (course?.chapters) {
      for (const chapter of course.chapters) {
        const lesson = chapter.lessons?.find(l => l.free)
        if (lesson) {
          freeLesson = lesson
          break
        }
      }
    }
    
    if (freeLesson) {
      this.onPlayVideo({ currentTarget: { dataset: { index: 0 } } })
    } else {
      wx.showToast({
        title: '暂无试听内容',
        icon: 'none'
      })
    }
  },

  /**
   * 推荐课程点击
   */
  onRecommendCourseItem(e) {
    const { id } = e.currentTarget.dataset
    Track.trackClick('recommend_course', 'navigation', { course_id: id })
    Router.navigateTo(`/packageTeacher/pages/courses/detail/index?id=${id}`)
  },

  /**
   * 查看全部评价
   */
  onViewAllComments() {
    Track.trackClick('course_comments_view_all', 'navigation', { courseId: this.data.courseId })
    // 可以跳转到评价列表页
  },

  /**
   * 展开/收起课程介绍
   */
  onToggleDescription() {
    this.setData({
      descriptionExpanded: !this.data.descriptionExpanded
    })
  },

  /**
   * 显示登录提示
   */
  showLoginTip() {
    wx.showModal({
      title: '提示',
      content: '请先登录后再进行此操作',
      confirmText: '去登录',
      success: (res) => {
        if (res.confirm) {
          Router.navigateTo('/pages/login/index')
        }
      }
    })
  },

  /**
   * 分享给朋友
   */
  onShareAppMessage() {
    const { course } = this.data
    return {
      title: course?.title || '精品课程推荐',
      desc: course?.subtitle || course?.description || '',
      path: `/packageTeacher/pages/courses/detail/index?id=${course?.id || this.data.courseId}`,
      imageUrl: course?.cover || '/images/share-default.jpg'
    }
  },

  /**
   * 分享到朋友圈
   */
  onShareTimeline() {
    const { course } = this.data
    return {
      title: course?.title || '精品课程推荐',
      desc: course?.subtitle || course?.description || '',
      path: `/packageTeacher/pages/courses/detail/index?id=${course?.id || this.data.courseId}`,
      imageUrl: course?.cover || '/images/share-default.jpg'
    }
  }
})
